package servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.jms.Connection;
import javax.jms.ConnectionFactory;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.activemq.ActiveMQConnectionFactory;

/**
 * Servlet implementation class AjaxServlet
 */
public class AjaxServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	protected String jmsServerUrl = "tcp://0.0.0.0:61616";
		   
	private static final String REQUEST_QUEUE_NAME = "jms/RequestQueue";
	private static final String REPLY_QUEUE_NAME = "jms/ReplyQueue";
	private static final String INVALID_QUEUE_NAME = "jms/InvalidQueue";

	private Connection connection;
	private Session session;
	private Destination replyQueue;
	private Destination invalidQueue;
	private MessageProducer requestProducer;
	private MessageConsumer replyConsumer;
	private MessageConsumer invalidConsumer;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		String messageTxt = request.getParameter("message");
		System.out.println(messageTxt);
		
		try{
		// Get connection factory for the local JMS server
	      ConnectionFactory connectionFactory = 
	         new ActiveMQConnectionFactory(jmsServerUrl);

	      // Get connection to the JMS server
	      System.out.println("Creating connection");
	      connection = connectionFactory.createConnection();

	      // Create a session on the connection that is not transacted
	      System.out.println("Creating session");
	      session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);

	      // Set up a message producer or consumer for each queue
	      Destination requestQueue = session.createQueue(REQUEST_QUEUE_NAME);
	      requestProducer = session.createProducer(requestQueue);
	      replyQueue = (Destination) session.createQueue(REPLY_QUEUE_NAME);
	      replyConsumer = session.createConsumer(replyQueue);
	      invalidQueue = (Destination) session.createQueue(INVALID_QUEUE_NAME);
	      invalidConsumer = session.createConsumer(invalidQueue);

	      // Enable receipt of messages on this connection
	      connection.start();
	      
	      // Clear any stale messages in the queues
	      clearQueue(invalidConsumer);
	      clearQueue(replyConsumer);
	      
	   // Send a message using the request queue
	      TextMessage requestMessage = session.createTextMessage();
	      requestMessage.setText(messageTxt);
	      requestMessage.setJMSReplyTo(replyQueue);
	      requestProducer.send(requestMessage);

	      // Output sent message
	      System.out.println("Sent request");
	      System.out.println("\tTime:       " + System.currentTimeMillis() + " ms");
	      System.out.println("\tMessage ID: " + requestMessage.getJMSMessageID());
	      System.out.println("\tCorrel. ID: "
	            + requestMessage.getJMSCorrelationID());
	      System.out.println("\tReply to:   " + requestMessage.getJMSReplyTo());
	      System.out.println("\tContents:   " + requestMessage.getText());

	      // Block until a reply is received on the reply queue
	      System.out.println("Waiting for response...");
	      Message msg = replyConsumer.receive();
	      if ( !(msg instanceof TextMessage)) {
	         System.out.println("Got message: " + msg);
	      }

	      // Output the reply message
	      TextMessage replyMessage = (TextMessage) msg;
	      System.out.println("Received reply ");
	      System.out.println("\tTime:       " + System.currentTimeMillis() + " ms");
	      System.out.println("\tMessage ID: " + replyMessage.getJMSMessageID());
	      System.out.println("\tCorrel. ID: " + replyMessage.getJMSCorrelationID());
	      System.out.println("\tReply to:   " + replyMessage.getJMSReplyTo());
	      System.out.println("\tContents:   " + replyMessage.getText());
	      
	      System.out.println("Closing connection.");
	      connection.close();
	      PrintWriter writer = response.getWriter(); 
	      writer.println(replyMessage.getText());
		 }catch (JMSException e) {
			// TODO: handle exception
        	e.printStackTrace();
		}
	}
	
	 private void clearQueue(MessageConsumer consumer) throws JMSException
	   {
	      Message msg;
	      do
	      {
	         System.out.println("Checking for stale message");
	         msg = consumer.receive(1);
	         if (msg != null)
	         {
	            System.out.println("Got message " + msg);
	         }
	      } while (msg != null);
	   }

}
